﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.ResourceManagement.ResourceProviders;
using UnityEngine.SceneManagement;

namespace Manager
{
    class MySceneManager : MonoBehaviour
    {
        [SerializeField] List<string> sceneAddress;
        [SerializeField] AssetReference reference;
        AsyncOperationHandle<SceneInstance> handle;
        int curIdx = -1;        
        public void LoadScene(int index)
        {
            curIdx =(curIdx+1) % sceneAddress.Count;
            if (index < 0 || index >= sceneAddress.Count)
            {
                Debug.LogError("Index out of range");
                return;
            }
            var lashHandle = handle;            
            handle = Addressables.LoadSceneAsync(sceneAddress[curIdx], LoadSceneMode.Additive);
            if (lashHandle.IsValid())
                handle.Completed += op =>
                {
                    if(op.Status == AsyncOperationStatus.Succeeded)
                        Addressables.UnloadSceneAsync(lashHandle);
                };
        }        

        private void OnDestroy()
        {            
            if(handle.IsValid())
                Addressables.UnloadSceneAsync(handle);
        }
    }
}
